﻿/**
 * 
 * Copyright 2009, 2010 Mike Jamer [email: mikejamer@gmail.com ]
 * 
 * This File is part of Moose IRC
 * 
 * MooseIRC is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * MooseIRC is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with MooseIRC.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;

namespace MooseIRC.Client.Status
{
    /// <summary>
    /// Moose IRC Status Client Window
    /// </summary>
    class Program
    {
        /// <summary>
        /// Socket to MooseIRC Client Server
        /// </summary>
        static Socket m_socket;

        /// <summary>
        /// Recieve Buffer
        /// </summary>
        static StringBuilder m_recieve_buffer;

        /// <summary>
        /// Application Entry
        /// </summary>
        /// <param name="args">Command Line Arguments</param>
        /// <remarks>
        /// In the long run, this will definately support remote locations,
        /// for the time being, this will have to spawn off additional clients, 
        /// to show things like channel/query windows...
        /// </remarks>
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();

            using (StatusForm frmStatus = new StatusForm())
            {
                Application.Run(frmStatus);
            }

            return;
        }

        /// <summary>
        /// Connect us to the server
        /// </summary>
        /// <param name="port"></param>
        static void connect_to_server(int port)
        {
            m_recieve_buffer = new StringBuilder();
            m_socket = create_socket();
            m_socket.Connect("127.0.0.1", port);

            recieve();

            return;
        }

        /// <summary>
        /// Create new socket
        /// </summary>
        /// <returns></returns>
        static Socket create_socket()
        {
            return new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

        static void send(string data)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(data);
            m_socket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, onSendComplete, buffer);
        }

        /// <summary>
        /// Fires when transmission completes
        /// </summary>
        /// <param name="result">Async. Result</param>
        static void onSendComplete(IAsyncResult result)
        {
            byte[] buffer = (byte[])result.AsyncState;
            int sent = m_socket.EndSend(result);
            if (sent != buffer.Length)
            {
                Console.WriteLine(">>>Transmission to server failed");
            }
            return;
        }

        /// <summary>
        /// Sets up recieve from server
        /// </summary>
        static void recieve()
        {
            byte[] buffer = new byte[512];
            m_socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, onRecieveComplete, buffer);
        }

        /// <summary>
        /// Fires when we recieve a new transmission from the server
        /// </summary>
        /// <param name="result">Async. Result</param>
        static void onRecieveComplete(IAsyncResult result)
        {
            byte[] buffer = (byte[])result.AsyncState;
            int recv = m_socket.EndReceive(result);
            m_recieve_buffer.Append(
                Encoding.UTF8.GetString(buffer, 0, recv));

            foreach (string line in processRecieveBuffer())
            {
                Console.WriteLine(line);
            }

            recieve();
            return;
        }

        /// <summary>
        /// Processes Recieve Buffer
        /// </summary>
        /// <returns>Array of all messages that have been completely recieved</returns>
        static string[] processRecieveBuffer()
        {
            List<string> responses = new List<string>();
            while (m_recieve_buffer.ToString().IndexOf("\r\n") != -1)
            {
                string buf = m_recieve_buffer.ToString();
                responses.Add(buf.Substring(0, buf.IndexOf("\r\n")));
                m_recieve_buffer.Remove(0,
                    buf.Substring(0, buf.IndexOf("\r\n")
                    ).Length + 2); //Remove message, plus the CRLF pair
            }
            return responses.ToArray();
        }

    }
}
